<?php

namespace Thenbsp\Wechat;

use Thenbsp\Wechat\Util\Curl;
use Thenbsp\Wechat\Util\Json;
use Thenbsp\Wechat\Exception\OAuthException;

/**
 * 网页授权
 * Created by thenbsp (thenbsp@gmail.com)
 * Created at 2015/07/23
 */
class User
{
    /**
     * 获取用户信息接口
     */
    const USERINFO_URL = 'https://api.weixin.qq.com/sns/userinfo?access_token';

    /**
     * 用户参数
     */
    protected $params;

    /**
     * 构造方法
     */
    function __construct($accessToken, $openid)
    {
        $params = array(
            'access_token'  => $accessToken,
            'openid'        => $openid
        );

        $curl       = new Curl;
        $response   = $curl->get(static::USERINFO_URL, $params);

        if( empty($response) ) {
            throw new OAuthException('Get Userinfo Failure: '.$curl->error());
        }

        $object = Json::decode($response);

        if( !(isset($object->openid) ||
            isset($object->nickname) ||
            isset($object->headimgurl)) ) {

            throw new OAuthException($object->errcode.': '.$object->errmsg);
        }

        $this->params = $object;
    }

    /**
     * 检测是否包含指定参数
     */
    public function hasParams($paramName)
    {
        return property_exists($this->params, $paramName);
    }

    /**
     * 获取参数
     */
    public function getParams($paramName = null, $default = null)
    {
        if( !is_null($paramName) ) {
            return $this->hasParams($paramName) ?
                $this->params->$paramName : $default;
        }
        return $this->params;
    }

    /**
     * 魔术方法
     */
    public function __get($key)
    {
        if( !$this->hasParams($key) ) {
            throw new OAuthException(sprintf('Undefined property: %s', $key));
        }

        return $this->getParams($key);
    }

}